package thread;

import java.sql.SQLOutput;

/**
 * 并发的缺陷，不能同时试衣服，也不能单线程，解决方法，在需要单线程时加上synchronized语句块，
 * 使方法块里的语句单线程执行
 * 两个人抢厕所，先进去的人出来后，其他人才能进
 */
public class SyncDemo2 {
    public static void main(String[] args) {
    Shop shop1 = new Shop();
    Shop shop2 = new Shop();
    Thread t1 = new Thread("钢铁侠"){
      public void run(){
//          shop.buy();
          shop1.buy();
      }
    };
    Thread t2 = new Thread("绿巨人"){
        public void run(){
//            shop.buy();
            shop2.buy();
        }
    };
    t1.start();
    t2.start();
    }
}
class Shop{
    public  void buy() {

        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + ":挑衣服");
            Thread.sleep(5000);
            //只有这个地方才需要排队
//            synchronized ("hello"){
            synchronized (this){
//            synchronized (new Object()){

                System.out.println(t.getName() + "：试衣服");
                Thread.sleep(5000);
            }
            System.out.println("结账离开");
        } catch (InterruptedException e) {
           e.printStackTrace();
        }
    }
}